package org.ponly.uno4j.core.impl;

import com.sun.star.lib.uno.helper.UnoUrl;
import org.ponly.uno4j.core.UnoBridge;
import org.ponly.uno4j.core.UnoClient;
import org.ponly.uno4j.core.UnoTask;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import static org.ponly.uno4j.util.UnoUtils.parseUnoUrl;

/**
 * 使用单一 UnoBridge 串行处理任务的 UnoClient 实现(UnoBridge不能并行处理)
 *
 * @author vacoor
 */
public class UnoClientImpl implements UnoClient {
    private UnoBridge unoBridge;
    private ExecutorService executorService;

    public UnoClientImpl(String urlUrl) {
        this(parseUnoUrl(urlUrl));
    }

    public UnoClientImpl(UnoUrl unoUrl) {
        unoBridge = new UnoBridge(unoUrl);
        executorService = Executors.newSingleThreadExecutor();
    }

    /**
     * {@inheritDoc}
     */
    public Future<?> submit(final UnoTask unoTask) {
        Runnable task = new Runnable() {
            @Override
            public void run() {
                try {
                    unoTask.process(unoBridge);
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            }
        };
        return executorService.submit(task);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void shutdown() {
        executorService.shutdown();
        unoBridge.disconnect();
    }

    public String getUnoUrl() {
        return unoBridge.getBridgeUrl();
    }
}
